use hypers::hyper::StatusCode;
use hypers::prelude::{hook, Next, Request, Responder, Response};

static USER_NAME: &str = "admin";
static PASS_WORD: &str = "123456";

static LOGIN_HTML: &str = r#"<!DOCTYPE html>
<html>
    <head>
        <title>swagger-ui login</title>
    </head>
    <style>
        html,body{
            margin:0;
            padding:0;
            width:100%;
            height:100%;
        }
        .container{
            display:flex;
            align-item:center;
            justify-content:center;
        }
        .form{
            display:flex;
            align-item:center;
            justify-content:center;
            flex-direction:column;
        }
        .mt-20{
            margin-top: 20px;
        }

    </style>
    <body class="container">
        <form class="form" action="/swaggerLogin" method="post">
            <h1>swagger-ui</h1>
            <input type="text" name="username" placeholder="用户名" />
            <input class="mt-20" type="password" name="password" placeholder="密码" />
            <button class="mt-20" type="submit" id="submit">登录</button>
        </form>
    </body>
</html>
"#;

#[hook]
pub async fn auth_token(req: Request, next: Next<'_>) -> impl Responder {
    if let Some(_) = req.get::<String>("swagger-auth") {
        return next.next(req).await;
    } else {
        let mut res = Response::default();
        res.html(LOGIN_HTML);
        return res;
    }
}

pub async fn swagger_login(mut req: Request) -> impl Responder {
    let username = req.form::<String>("username").await;
    let password = req.form::<String>("password").await;
    let mut res = Response::default();
    if let (Some(name), Some(pass)) = (username, password) {
        if name.eq(USER_NAME) && pass.eq(PASS_WORD) {
            req.insert("swagger-auth", "salvo-admin");
            res.redirect(StatusCode::SEE_OTHER, "/doc/swagger_ui/");
            return res;
        }
    }
    res.html(LOGIN_HTML);
    return res;
}
